package com.jt.service;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jt.mapper.RoleMapper;
import com.jt.pojo.Role;
import com.jt.pojo.User;
import com.jt.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @Author Happy Nest-ZhangJian
 * @Date 2021/12/8
 * @Update 2021/12/8 16:46
 * @Version 1.0
 */
@Service
public class RoleServiceImpl implements RoleService{
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public PageResult getRoleList(PageResult pageResult) {
        //1.构建分页对象  参数1: 第几页   参数2: 多少条
        Page<Role> page = new Page<>(pageResult.getPageNum(),pageResult.getPageSize());
        //2.准备条件构造器 构建模糊查询
        QueryWrapper queryWrapper = new QueryWrapper();
        String query = pageResult.getQuery();
        boolean flag = StringUtils.hasLength(query);
        queryWrapper.like(flag,"role_name",query);

        //3.根据MP查询 实现分页数据的自动封装
        page = roleMapper.selectPage(page,queryWrapper);

        //4.获取数据,返回分页对象
        long total = page.getTotal();
        //获取分页结果
        List<Role> rows = page.getRecords();
        return pageResult.setTotal(total).setRows(rows);
    }

    @Transactional
    @Override
    public void updateRoleStatus(Role role) {
        roleMapper.updateById(role);
    }

    @Transactional
    @Override
    public void saveItem(Role role) {
        role.setRoleStatus(true);
        roleMapper.insert(role);
    }

    @Override
    public Role findRoleById(Integer roleId) {
        return roleMapper.selectById(roleId);
    }

    @Transactional
    @Override
    public void updateRole(Role role) {
        role.setUpdated(new Date());
        roleMapper.updateById(role);
    }

    @Transactional
    @Override
    public void deleteRoleById(Integer id) {
        roleMapper.deleteById(id);
    }

    @Override
    public String login(Role role) {
        //1.将密码加密处理
        String password = role.getRolePassword();
        //2.利用md5加密算法 进行加密
        String md5Pass = DigestUtils.md5DigestAsHex(password.getBytes());
        role.setRolePassword(md5Pass);
        //3.查询数据库数据
        Wrapper<Role> roleWrapper = new QueryWrapper<>(role);
        Role roleDB = roleMapper.selectOne(roleWrapper);
        //roleMapper.selectOne(new QueryWrapper<>().eq("role_password", role.getRolePassword()));
        if(roleDB == null){
            //说明: 用户名和密码错误
            return null;
        }
        //说明: 用户名和密码正确,返回秘钥
        String uuid = UUID.randomUUID().toString()
                .replace("-","");
        return uuid;
    }
}
